import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
from PyQt5 import QtGui


from bisheMainWin import Ui_MainWindow

from label import Ui_Dialog

from YOLOv4.utils.utils import *
from YOLOv4.tool.darknet2pytorch import Darknet

import xlwt
from xlwt import Workbook
import xlrd
import xlwt
from xlutils.copy import copy

import os
import cv2

i=1

def getFileList(dir, Filelist, ext=None):
    """
    获取文件夹及其子文件夹中文件列表
    输入 dir：文件夹根目录
    输入 ext: 扩展名
    返回： 文件路径列表
    """
    newDir = dir
    if os.path.isfile(dir):
        if ext is None:
            Filelist.append(dir)
        else:
            if ext in dir[-3:]:
                Filelist.append(dir)

    elif os.path.isdir(dir):
        for s in os.listdir(dir):
            newDir = os.path.join(dir, s)
            getFileList(newDir, Filelist, ext)

    return Filelist

class MainWindow(QMainWindow, Ui_MainWindow):  # 多重继承QMainWindow和Ui_MainWindow
    def __init__(self):
        super(MainWindow, self).__init__()  # 先调用父类QMainWindow的初始化方法
        self.setupUi(self)  # 再调用setupUi方法
        self.setWindowTitle('智能目标辅助标定平台')
        self.selectFolder=""   #选中的文件夹
        self.saveFolder=""    #存储的文件夹
        self.nowImage=""   #当前的图片路径
        self.scale=0    #当前的尺寸大小
        self.mode=0    #文件存储模式：0：line(同一个文件夹中)，1：tree(根据原来的文件层次)
        self.saveXls=""  #该图片对应的xls的位置


        self.imageList=[]

        self.tmpXls=[]

        self.rect = None

        # self.Image = QLabel(self)
        # self.vbox = QVBoxLayout()
        # self.vbox.addWidget(self.Image)
        # self.scrollAreaWidgetContents.setLayout(self.vbox)

        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator(self)
        validator.setRegExp(reg)
        self.scaleEdit.setValidator(validator)

        self.setFixedSize(self.width(), self.height())

        #self.Image = MyLabel(self.scrollAreaWidgetContents)  # 重定义的label
        #grid_layout = QGridLayout()
        #grid_layout.addWidget(self.Image)
        #self.scrollArea.setLayout(grid_layout)
        #self.scrollArea.setWidget(self.scrollAreaWidgetContents)






        #self.scrollAreaWidgetContents.setFixedSize(self.scrollAreaWidgetContents.width(),self.scrollAreaWidgetContents.height())



    def openImage(self):

        imgName, imgType = QFileDialog.getOpenFileName(self, "上传图片", "", "*.jpg;;*.png;;All Files(*)")
        scale=0
        if(imgName!=""):

            #self.nowImage=imgName
            self.file_listWidget.clear()

            book = Workbook(encoding='utf-8')
            sheet1 = book.add_sheet('Sheet 1')

            sheet1.write(0, 0, "id")
            sheet1.write(0, 1, "imageName")
            sheet1.write(0, 2, "isShow")
            sheet1.write(0, 3, "class")
            sheet1.write(0, 4, "color")
            sheet1.write(0, 5, "x")
            sheet1.write(0, 6, "y")
            sheet1.write(0, 7, "width")
            sheet1.write(0, 8, "height")

            # 保存Excel book.save('path/文件名称.xls')
            book.save(imgName.replace("."+imgName.split("/")[-1].split(".")[-1],"_tmp.xls"))
            self.tmpXls.append(imgName.replace("."+imgName.split("/")[-1].split(".")[-1],"_tmp.xls"))



            self.file_listWidget.insertItem(0, "图片名:" + imgName.split("/")[-1] + "   路径:" + imgName)
            self.selectFolder=imgName.replace("/"+imgName.split("/")[-1],"")


            self.file_listWidget.setCurrentRow(0)

            #self.sacleChange()

            # print("11111")
            # print(jpg.width(),jpg.height())
            # print(self.Image.width(), self.Image.height())
            # print(scale_width, self.Image.height()-20)
            # self.scaleEdit.setText(str(int(round(1 / scale * 100))))





    def openFolder(self):

        fd = QFileDialog.getExistingDirectory(self.centralwidget, "选择文件夹", "")
        #print(fd)
        self.selectFolder=fd
        self.scrollAreaWidgetContents.setMaximumWidth(629)
        self.scrollAreaWidgetContents.setMaximumHeight(629)
        imglist1 = getFileList(fd, [], 'jpg')
        imglist2 = getFileList(fd, [], 'png')
        imglist=imglist1+imglist2
        if(len(imglist)!=0):
            if (len(self.tmpXls) != 0):
                for i in range(len(self.tmpXls)):
                    os.remove(self.tmpXls[i])
                self.tmpXls.clear()


            for i in range(len(imglist)):
                imglist[i]=imglist[i].replace("\\","/")

                self.file_listWidget.insertItem(i,"图片名:"+imglist[i].split("/")[-1]+"   路径:"+imglist[i])


                self.tmpXls.append(imglist[i].replace("." + imglist[i].split("/")[-1].split(".")[-1], "_tmp.xls"))

            self.file_listWidget.setCurrentRow(0)
            self.imageList=imglist

    def saveFolderSelect(self):
        #assert 1 == 3
        fd=""
        while(fd==""):
            fd = QFileDialog.getExistingDirectory(self.centralwidget, "选择文件夹", "")
        print(fd)
        flag=1
        for i in range(self.SaveFolder_listWidget.count()):
            #print(self.SaveFolder_listWidget.item(i).text())
            if(self.SaveFolder_listWidget.item(i).text()==fd):
                self.SaveFolder_listWidget.setCurrentRow(i)
                flag=0
        if(flag==0):
            msgBox = QMessageBox()
            msgBox.setWindowTitle('提示')
            msgBox.setText("该存储位置已录入！\n已帮您自动切换")
            msgBox.exec_()
        if(flag==1):
            self.SaveFolder_listWidget.insertItem(self.SaveFolder_listWidget.count(),fd)
            self.saveFolder=fd
            self.SaveFolder_listWidget.setCurrentRow(self.SaveFolder_listWidget.count()-1)

            if (self.lineButton.isChecked()):
                self.mode = 0
            else:
                self.mode = 1
            #print("---------")
            if (self.mode == 0):
                savexls = self.saveFolder + "/" + self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1],
                                                                                       "xls")
            else:
                savexls = self.nowImage.replace(self.selectFolder, self.saveFolder) + "/" + \
                          self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1], "xls")
            self.saveXls=savexls
            self.Image.setInfo(self.nowImage,self.saveXls,self.scale)


    def selectImage(self,txt):
        #assert 1 == 4

        if (txt!=""):
            self.scrollAreaWidgetContents.setMaximumWidth(629)
            self.scrollAreaWidgetContents.setMaximumHeight(629)
            txt=txt.split("路径:")[-1]
            if(txt!=self.nowImage):
                #print(txt)

                self.nowImage =txt
                jpg = QPixmap(txt)  # .scaled(self.label_has_image.width(), self.label_has_image.height())
                # print(imgName)


                #self.Image.setGeometry(0, 0, 629, 629)
                if (jpg.width() >= jpg.height()):

                    scale = jpg.width() / 629
                    self.scaleEdit.setText(str(int(round(1/scale* 100))))
                    self.scale=int(round(1/scale* 100))
                    # print(self.Image.width())
                    scale_height = jpg.height() / scale
                    self.Image.setGeometry(10, (629 - scale_height) / 2, 629,
                                           scale_height)
                    self.Image.setMaximumWidth(629)
                    self.Image.setMaximumHeight(scale_height)
                else:
                    scale = jpg.height() / 629
                    scale_width = jpg.width() / scale
                    self.scaleEdit.setText(str(int(round(1/scale* 100))))
                    self.scale = int(round(1 / scale * 100))
                    self.Image.setGeometry((629 - scale_width) / 2, 10, scale_width,
                                           629)
                    self.Image.setMaximumWidth(scale_width)
                    self.Image.setMaximumHeight(629)

                # opencv_img = cv2.imread(txt)
                # opencv_img = cv2.cvtColor(opencv_img, cv2.COLOR_BGR2RGB)
                # self.QtImg = QtGui.QImage(opencv_img.data,
                #                           opencv_img.shape[1],
                #                           opencv_img.shape[0],
                #                           opencv_img.shape[1] * 3,
                #                           QtGui.QImage.Format_RGB888)
                #
                # self.label.setPixmap(QtGui.QPixmap.fromImage(self.QtImg))


                self.Image.setPixmap(jpg)
                self.Image.setScaledContents(True)

                if(self.saveFolder==""):
                    while (1):

                        reply = QMessageBox.question(self, '存储文件', '当前存储位置为空，请选择',
                                                     QMessageBox.Yes)
                        if reply == QMessageBox.Yes:
                            self.saveFolderSelect()
                            break

                if (self.mode == 0):
                    savexls = self.saveFolder + "/" + self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1],
                                                                                           "xls")
                else:
                    savexls = self.nowImage.replace(self.selectFolder, self.saveFolder) + "/" + \
                              self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1], "xls")
                #print(savexls)
                self.saveXls=savexls
                #print(savexls)
                if(os.path.exists(savexls)):
                    self.box = QMessageBox(QMessageBox.Question, 'label', '在此存储位置内已有label标签\n请选择加载label，覆盖原label，重新选择存储位置')

                    # 添加按钮，可用中文
                    load = self.box.addButton('加载label', QMessageBox.ActionRole)
                    remove = self.box.addButton('覆盖原label', QMessageBox.ActionRole)
                    reSelect = self.box.addButton('重新选择存储位置', QMessageBox.ActionRole)

                    self.box.exec_()

                    result=self.box.clickedButton()
                    #print(result)
                    if result == load:
                        msgBox = QMessageBox()
                        msgBox.setWindowTitle('提示')
                        msgBox.setText("label加载成功")
                        msgBox.exec_()
                        data = xlrd.open_workbook(savexls)
                        data.sheet_names()
                        table = data.sheet_by_name('Sheet 1')
                        name = table.name
                        rowNum = table.nrows
                        colNum = table.ncols
                        tmp=[]
                        for i in range(1,int(rowNum)):
                            color=table.cell(i, 4).value
                            objectClass=table.cell(i, 3).value
                            if(objectClass in tmp):
                                continue
                            tmp.append(objectClass)
                            self.tmpQlabel=QLabel(objectClass)

                            pe = QPalette()
                            color = QColor(color)
                            pe.setColor(QPalette.WindowText, color)  # 设置字体颜色
                            # pe.setColor(QPalette.Background,Qt.blue)<span style="font-family: Arial, Helvetica, sans-serif;">#设置背景颜色，和上面一行的效果一样
                            self.tmpQlabel.setPalette(pe)
                            self.widgetItem=QListWidgetItem
                            self.label_listWidget.insertItem(self.label_listWidget.count(),self.tmpQlabel)
                    elif result == remove:
                        os.remove(savexls)
                        book = Workbook(encoding='utf-8')
                        sheet1 = book.add_sheet('Sheet 1')

                        sheet1.write(0, 0, "id")
                        sheet1.write(0, 1, "imageName")
                        sheet1.write(0, 2, "isShow")
                        sheet1.write(0, 3, "class")
                        sheet1.write(0, 4, "color")
                        sheet1.write(0, 5, "x")
                        sheet1.write(0, 6, "y")
                        sheet1.write(0, 7, "width")
                        sheet1.write(0, 8, "height")

                        # 保存Excel book.save('path/文件名称.xls')
                        book.save(self.saveXls)

                    elif result == reSelect:
                        self.saveFolderSelect()
                        book = Workbook(encoding='utf-8')
                        sheet1 = book.add_sheet('Sheet 1')

                        sheet1.write(0, 0, "id")
                        sheet1.write(0, 1, "imageName")
                        sheet1.write(0, 2, "isShow")
                        sheet1.write(0, 3, "class")
                        sheet1.write(0, 4, "color")
                        sheet1.write(0, 5, "x")
                        sheet1.write(0, 6, "y")
                        sheet1.write(0, 7, "width")
                        sheet1.write(0, 8, "height")

                        # 保存Excel book.save('path/文件名称.xls')
                        book.save(self.saveXls)
                else:
                    book = Workbook(encoding='utf-8')
                    sheet1 = book.add_sheet('Sheet 1')

                    sheet1.write(0, 0, "id")
                    sheet1.write(0, 1, "imageName")
                    sheet1.write(0, 2, "isShow")
                    sheet1.write(0, 3, "class")
                    sheet1.write(0, 4, "color")
                    sheet1.write(0, 5, "x")
                    sheet1.write(0, 6, "y")
                    sheet1.write(0, 7, "width")
                    sheet1.write(0, 8, "height")

                    # 保存Excel book.save('path/文件名称.xls')
                    book.save(self.saveXls)

                if (self.lineButton.isChecked()):
                    self.mode = 0
                else:
                    self.mode = 1
                # print("---------")
                if (self.mode == 0):
                    savexls = self.saveFolder + "/" + self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1],
                                                                                           "xls")
                else:
                    savexls = self.nowImage.replace(self.selectFolder, self.saveFolder) + "/" + \
                              self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1], "xls")
                self.saveXls = savexls
                self.Image.setInfo(self.nowImage, self.saveXls, self.scale)
                self.Image.setCursor(Qt.CrossCursor)


    def searchImage(self):
        #assert 1 == 5
        text = self.searchEdit.text()
        fd=self.selectFolder
        self.file_listWidget.clear()
        #print("11111")
        imglist1 = getFileList(fd, [], 'jpg')
        imglist2 = getFileList(fd, [], 'png')
        imglist3 = imglist1 + imglist2
        imglist = []
        for i in range(len(imglist3)):
            if text in imglist3[i]:
                imglist.append(imglist3[i])
        if (len(imglist) != 0):

            for i in range(len(imglist)):
                imglist[i] = imglist[i].replace("\\", "/")
                self.file_listWidget.insertItem(i, "图片名:" + imglist[i].split("/")[-1] + "   路径:" + imglist[i])

            self.file_listWidget.setCurrentRow(0)

    def nextImage(self):
        #assert 1 == 6
        if (self.file_listWidget.count() > 1):
            nowIndexList = self.file_listWidget.selectedIndexes()
            nowIndex = nowIndexList[0].row()
            # print(nowIndex)
            if (nowIndex != (self.file_listWidget.count() - 1)):
                prevIndex = nowIndex + 1
                self.file_listWidget.setCurrentRow(prevIndex)

    def prevImage(self):
        #assert 1 == 7
        if(self.file_listWidget.count()>1 ):
            nowIndexList = self.file_listWidget.selectedIndexes()
            nowIndex=nowIndexList[0].row()
            #print(nowIndex)
            if (nowIndex != 0):
                prevIndex = nowIndex - 1
                self.file_listWidget.setCurrentRow(prevIndex)

    def sacleChange(self):
        #assert 1 == 8
        imgName=self.nowImage
        if(imgName!=""):
            #self.scrollAreaWidgetContents.setGeometry(0,0,629,629)

            scale=self.scaleEdit.text()
            if(scale==""):
                scale=0
            #print("test")
            self.scale = float(scale)
            scale=float(scale)/100
            jpg = QPixmap(imgName)

            # self.Image.resize(629, 629)
            # print(self.Image.size[0]+"，"+self.Image.size[1])
            # print(self.Image.width())
            scale_height = jpg.height() * scale
            scale_width = jpg.width() * scale
            #print("test1:", self.Image.height(), self.Image.width())
            if (scale_height < 629 and scale_width < 629):
                #print("test3:", self.Image.height(), self.Image.width())
                self.scrollAreaWidgetContents.setMaximumWidth(629)
                self.scrollAreaWidgetContents.setMaximumHeight(629)
                #print("test31:", self.Image.height(), self.Image.width())
            else:

                self.scrollAreaWidgetContents.setMaximumWidth(scale_width)
                self.scrollAreaWidgetContents.setMaximumHeight(scale_height)
            self.Image.setMaximumWidth(scale_width)
            self.Image.setMaximumHeight(scale_height)
            if (jpg.width() >= jpg.height()):

                if(scale_height>629):

                    self.Image.setGeometry(10, 10, scale_width, scale_height)

                else:
                    if (scale_width<629):
                        self.Image.setGeometry((629 - scale_width) / 2, (629 - scale_height) / 2, scale_width, scale_height)

                    else:
                        self.Image.setGeometry(10,(629 - scale_height) / 2 , scale_width, scale_height)

            else:

                if(scale_width>629):
                    self.Image.setGeometry(10, 10, scale_width, scale_height)
                    #print("1")
                else:
                    if(scale_height<629):
                        self.Image.setGeometry((629 - scale_width) / 2, (629 - scale_height) / 2, scale_width,
                                               scale_height)
                        #print("2")

                    else:
                        self.Image.setGeometry((629 - scale_width) / 2,10 , scale_width, scale_height)
                        # print(scale_width)
                        # print((629 - scale_width) / 2)
                        # print("3")
                    #print("test2:", self.Image.height(), self.Image.width())
                # self.Image.resize(scale_width, self.Image.height() - 20)
                #print(self.Image.width(), self.Image.height())
                # self.Image.setMaximumWidth(scale_width)
                # self.Image.setMaximumHeight(self.Image.height() - 20)
                #(self.Image.height() - 20)

            #self.scrollArea.setWidget(self.Image)

            #print("test4:", self.Image.height(), self.Image.width())
            #self.Image.resize(scale_width,scale_height)
            self.file_listWidget.clear()
            self.file_listWidget.insertItem(0, "图片名:" + imgName.split("/")[-1] + "   路径:" + imgName)
            self.selectFolder = imgName.replace("/" + imgName.split("/")[-1], "")
            #print("test5:",self.Image.height(),self.Image.width())

            if (self.lineButton.isChecked()):
                self.mode = 0
            else:
                self.mode = 1
            # print("---------")
            if (self.mode == 0):
                savexls = self.saveFolder + "/" + self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1],
                                                                                       "xls")
            else:
                savexls = self.nowImage.replace(self.selectFolder, self.saveFolder) + "/" + \
                          self.nowImage.split("/")[-1].replace(self.nowImage.split(".")[-1], "xls")
            self.saveXls = savexls
            self.Image.setInfo(self.nowImage, self.saveXls, self.scale)
            self.Image.update()

    def keyPressEvent(self, QKeyEvent):  # 键盘某个键被按下时调用
        # 参数1  控件
        if QKeyEvent.key() == Qt.Key_A:  # 判断是否按下了A键
            # key()  是普通键

            self.prevImage()

        if QKeyEvent.key() == Qt.Key_D:  # 判断是否按下了A键
            # key()  是普通键
            self.nextImage()

    def wheelEvent(self, event):
        angle = event.angleDelta() / 8  # 返回QPoint对象，为滚轮转过的数值，单位为1/8度
        angleX = angle.x()  # 水平滚过的距离(此处用不上)
        angleY = angle.y()  # 竖直滚过的距离
        if angleY > 0:
            #self.setText("滚轮向上滚动的事件: 自己定义")
            #print("鼠标滚轮上滚")  # 响应测试语句
            scale = self.scaleEdit.text()
            if(scale!=""):
                self.scaleEdit.setText(str(int(scale)+1))
                self.sacleChange()
        else:  # 滚轮下滚
            #self.setText("滚轮向下滚动的事件: 自己定义")
            #print("鼠标滚轮下滚")  # 响应测试语句
            scale = self.scaleEdit.text()
            if (scale != ""):
                self.scaleEdit.setText(str(int(scale) - 1))
                self.sacleChange()

    def detection(self):
        if(len(self.imageList)!=0):
            cfgfile = "YOLOv4/cfg/yolov4.cfg"
            weightfile = "YOLOv4/weight/yolov4.weights"
            #imgfile = sys.argv[3]
            m = Darknet(cfgfile)

            m.print_network()
            m.load_weights(weightfile)
            print('Loading weights from %s... Done!' % (weightfile))


            namesfile = 'data/coco.names'


            use_cuda = 0
            if use_cuda:
                m.cuda()

            imgfiles=self.imageList
            for i in range(len(imgfiles)):
                imgfile=imgfiles[i]
                img = Image.open(imgfile).convert('RGB')
                sized = img.resize((m.width, m.height))


                start = time.time()
                boxes = do_detect(m, sized, 0.5, 0.4, use_cuda)
                finish = time.time()

                print('%s: Predicted in %f seconds.' % (imgfile, (finish - start)))

                class_names = load_class_names(namesfile)
                plot_boxes(img, boxes, 'predictions.jpg', class_names)

    def closeEvent(self, event):
        if (len(self.tmpXls) != 0):
            for i in range(len(self.tmpXls)):
                os.remove(self.tmpXls[i])
            self.tmpXls.clear()
        # reply = QtWidgets.QMessageBox.question(self, '警告', '退出后测试将停止,\n你确认要退出吗？',
        #                                        QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
        # if reply == QtWidgets.QMessageBox.Yes:
        #     event.accept()
        # else:
        #     event.ignore()





class MyLabel(QLabel):
    x0 = 0
    y0 = 0
    x1 = 0
    y1 = 0
    flag = False


    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.savexls = ""  # 存储的xls位置
        self.nowImage=""
        self.scale = 0  # 当前的尺寸大小

        self.stop=0


    # 鼠标点击事件
    def mousePressEvent(self, event):
        if (self.nowImage != ""):
            self.flag = True
            self.x0 = event.x()
            self.y0 = event.y()

    # 鼠标释放事件
    def mouseReleaseEvent(self, event):

        if (self.nowImage != ""):
                #print(self.savexls)
                self.flag = False
                self.label = Dialog()

                self.label.show()
                if self.label.exec_() == QtWidgets.QDialog.Accepted:
                    savexls=self.savexls
                    old_excel = xlrd.open_workbook(savexls, formatting_info=True)

                    old_excel.sheet_names()
                    table = old_excel.sheet_by_name('Sheet 1')
                    name = table.name
                    rowNum = table.nrows
                    colNum = table.ncols

                    # 将操作文件对象拷贝，变成可写的workbook对象
                    new_excel = copy(old_excel)
                    # 获得第一个sheet的对象
                    ws = new_excel.get_sheet(0)
                    # 写入数据
                    ws.write(rowNum, 0, self.label.IDedit.text())
                    ws.write(rowNum, 1, self.nowImage.split("/")[-1])
                    ws.write(rowNum, 2, 1)
                    ws.write(rowNum, 3, self.label.classEdit.text())
                    ws.write(rowNum, 4, self.label.color)
                    ws.write(rowNum, 5, self.x0 /(self.scale/100))
                    ws.write(rowNum, 6, self.y0/(self.scale/100))
                    ws.write(rowNum, 7, self.x1/(self.scale/100) - self.x0/(self.scale/100))
                    ws.write(rowNum, 8, self.y1/(self.scale/100) - self.y0/(self.scale/100))
                    # 另存为excel文件，并将文件命名

                    # if(os.path.exists(savexls)):
                    #     data = xlrd.open_workbook(savexls)
                    #     data.sheet_names()
                    #     table = data.sheet_by_name('Sheet1')
                    #     name = table.name
                    #     rowNum = table.nrows
                    #     colNum = table.ncols
                    #     for i in range(1,rowNum):
                    #         color=table.cell(i, j).value
                    new_excel.save(savexls)








    # 鼠标移动事件
    def mouseMoveEvent(self, event):
        if (self.nowImage != ""):
            if self.flag:
                self.x1 = event.x()
                self.y1 = event.y()
                self.update()

    # 绘制事件
    def paintEvent(self, event):
        if(self.nowImage!=""):

            super().paintEvent(event)
            rect = QRect(self.x0, self.y0, self.x1 - self.x0, self.y1 - self.y0)
            painter = QPainter(self)

            painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
            painter.drawRect(rect)
            if(os.path.exists(self.savexls)):
                #print(self.savexls)
                data = xlrd.open_workbook(self.savexls)
                data.sheet_names()
                table = data.sheet_by_name('Sheet 1')
                name = table.name
                rowNum = table.nrows
                colNum = table.ncols
                if(rowNum>1):
                    #print(self.scale)
                    for i in range(1,rowNum):
                        color = QColor(table.cell(i,4).value)
                        painter.setPen(QPen(color, 2, Qt.SolidLine))
                        #print(type(self.scale))
                        rect = QRect(int(table.cell(i,5).value)*(self.scale/100), int(table.cell(i,6).value)*(self.scale/100), int(table.cell(i,7).value)*(self.scale/100), int(table.cell(i,8).value)*(self.scale/100))
                        painter.drawRect(rect)




                    #painter.drawRect(QRect(100,100,200,300))

    def setInfo(self,nowImage,savexls,scale):
        self.nowImage=nowImage
        self.savexls=savexls
        self.scale=scale
        self.update()
        #print(savexls)



class Dialog(QtWidgets.QDialog,Ui_Dialog):
    def __init__(self):
        super(Dialog, self).__init__()
        self.setupUi(self)
        self.setWindowTitle('标注设置')
        self.setFixedSize(self.width(), self.height())
        #self.ok=0
        self.color=""

    def colorSelect(self):

        c = QColorDialog.getColor()

        # pixmap=QPixmap(10,10)
        # pixmap.fill(c)
        Sheet="background-color: "+str(c.name())+";"
        #Sheet="background-color: rgb(255, 170, 0);"
        #print(Sheet)
        #self.colorButton.setIcon(QIcon(pixmap))
        self.colorButton.setStyleSheet(Sheet)
        #self.colorButton.setStyleSheet("background-color: red")
        # self.color=str(c.name())
        # print(c.name())
        self.color=c.name()

    #def accept(self):

        #self.close()

    # def accepted(self) -> None:
    #     self.ok = 1
    #
    # #def reject(self):
    #     #self.ok=0
    #     #self.close()
    # def rejected(self) -> None:
    #     self.ok=0

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = MainWindow()

    ui.show()
    sys.exit(app.exec_())
